package com.company.psm.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.company.psm.entity.Bill;
import com.company.psm.entity.Medicine;
import com.company.psm.entity.Store;
import com.company.psm.entity.User;
import com.company.psm.service.BillManagement;
import com.company.psm.service.MedicineManagement;
import com.company.psm.service.StoreManagement;
import com.company.psm.service.UserManagement;
import com.company.psm.util.Util;

@Controller
@RequestMapping("/bill")
public class BillController {
	@Autowired
	private BillManagement billManagement;
	@Autowired
	private MedicineManagement medicineManagement;
	@Autowired
	private UserManagement userManagement;
	@Autowired
	private StoreManagement storeManagement;

	@RequestMapping(method = RequestMethod.GET, value = "list")
	public ModelAndView getAllBills(@RequestParam(value="listAll", required=false) String listAll) {
		ModelAndView mav = new ModelAndView();
		Long storeId = getCurrentUser().getStore().getId();
		List<Bill> bills = new ArrayList<Bill>();
		List<User> users = userManagement.getAllStoreUserByRole(storeId, "ROLE_SALE_STAFF");
		System.err.println("Users size = " + users.size());
		mav.addObject("users", users);
		mav.addObject("roleCode", getCurrentUser().getRole().getCode());
		if (listAll!=null && listAll.equals("listAllData")){
			if(getCurrentUser().getRole().getCode().equals("ROLE_STORE_OWNER")){
				bills = billManagement.getAllBillByStore(storeId);
			}else{
				bills = billManagement.getAllBillUser(getCurrentUser().getId());
			}
		}
		List<Medicine> medicines = medicineManagement.getMedicineByStoreId(storeId);
		mav.addObject("medicines", medicines);
		mav.addObject("staffs",userManagement.getAllStoreUserByRole(storeId, "ROLE_SALE_STAFF"));
		mav.setViewName("bill/list");
		mav.addObject("bills", bills);
		return mav;
	}

	@RequestMapping(method = RequestMethod.GET, value = "salemedicine")
	public ModelAndView SalelMedicine() {
		List<Medicine> medicines = medicineManagement.getAllMedicines();
		User user = this.getCurrentUser();
		ModelAndView model = new ModelAndView();
		model.setViewName("/bill/salemedicine");
		model.addObject("medicines", medicines);
		model.addObject("userName", user.getFullname());
		model.addObject("storeName", user.getStore().getStoreName());
		return model;
	}

	public User getCurrentUser() {
		Authentication authentication = SecurityContextHolder.getContext()
				.getAuthentication();
		String name = authentication.getName();
		return userManagement.getUserByAccount(name);
	}

	@SuppressWarnings("static-access")
	@RequestMapping(method = RequestMethod.GET, value = "create")
	public ModelAndView createBill(
			@RequestParam(value = "thoigiantaohoadon", required = false) String bill_Date,
			@RequestParam(value = "tencuahang", required = false) String storeName,
			@RequestParam(value = "sohoadon", required = false) String billNumber,
			@RequestParam(value = "nguoitaohoadon", required = false) String saleStaffName,
			@RequestParam(value = "tenkhachhang", required = false) String customerName,
			@RequestParam(value = "tongcongsotienkhachphaitra", required = false) String totalValue,
			@RequestParam(value = "tenthuoc", required = false) String medicineNameList,
			@RequestParam(value = "description", required = false) String desc) {

		List<Medicine> mdcLists = new ArrayList<Medicine>();

		List<String> mNList = this.toListName(medicineNameList);
		for (String string : mNList) {
			mdcLists.add(medicineManagement.getMedicineByName(string));
		}

		Store st = storeManagement.getStoreByName(storeName);

		billManagement.createBill(bill_Date, storeName, billNumber,
				saleStaffName, customerName, mdcLists, totalValue, st, desc,getCurrentUser());

		List<Bill> bills = billManagement.getAllBills();
		return new ModelAndView("/bill/list", "bills", bills);
	}

	public static List<String> toListName(String str) {
		List<String> result = new ArrayList<String>();
		String tmp[] = str.split(",");
		for (String name : tmp) {
			if (name != null && !name.equals("")) {
				result.add(name);
			}
		}
		return result;
	}

	@RequestMapping(method = RequestMethod.GET, value = "delete")
	public ModelAndView deleteBill(
			@RequestParam(value = "billId", required = false) long billId) {
		billManagement.deleteBill(billId);
		List<Bill> bills = billManagement.getAllBills();
		return new ModelAndView("/bill/list", "bills", bills);
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "searchByCustomerName")
	public ModelAndView getAllBillsByCustomer(
			@RequestParam(value="customerName", required=false) String customerName,
			@RequestParam(value="fromDate", required=false) String fromDate,
			@RequestParam(value="toDate", required=false) String toDate,
			@RequestParam(value="uId", required=false) String userId
			) {
		Long storeId = getCurrentUser().getStore().getId();
		ModelAndView mav = new ModelAndView();
		Date getDateFrom = null;
		Date getDateTo = null;
		if(fromDate == null || fromDate.equals("")){
			getDateFrom = null;
		}else{
			getDateFrom = Util.toDate(fromDate);
		}
		if(toDate == null || toDate.equals("")){
			getDateTo = new Date();
		}else{
			getDateTo = Util.toDate(toDate);
		}
		List<User> users = userManagement.getAllStoreUserByRole(storeId, "ROLE_SALE_STAFF");
		System.err.println("Users size = " + users.size());
		mav.addObject("users", users);
		List<Bill> bills = billManagement.searchBillByCustomerDate(customerName, storeId,getDateFrom,getDateTo,getCurrentUser(), userId);
		List<Medicine> medicines = medicineManagement.getMedicineByStoreId(storeId);
		mav.addObject("medicines", medicines);
		mav.addObject("roleCode", getCurrentUser().getRole().getCode());
		mav.addObject("customerName", customerName);
		mav.setViewName("bill/list");
		mav.addObject("bills", bills);
		mav.addObject("totalValue", getTotalPrice(bills));
		return mav;
	}
	@RequestMapping(method = RequestMethod.GET, value = "searchByDate")
	public ModelAndView getBillBetweenDate(
			@RequestParam(value="fromDate", required=false) String fromDate,
			@RequestParam(value="toDate", required=false) String toDate
			){
		ModelAndView mav = new ModelAndView();
		mav.setViewName("bill/list");
		mav.addObject("bills", getListBillByDate(fromDate, toDate));
		return mav;
	}
	
	public List<Bill> getListBillByDate(String fromDate, String toDate){
		Date getDateFrom = null;
		Date getDateTo = null;
		if(fromDate == null || fromDate.equals("")){
			getDateFrom = new Date();
		}else{
			getDateFrom = Util.toDate(fromDate);
		}
		if(toDate == null || toDate.equals("")){
			getDateTo = getDateFrom;
		}else{
			getDateTo = Util.toDate(toDate);
		}		
		Long storeId = getCurrentUser().getStore().getId();
		List<Bill> bills = billManagement.searchBillByDateAndStore(getDateFrom, getDateTo, storeId);
		return bills;
	}
	
	public String getTotalPrice(List<Bill> bills){
		double totalPricce = 0;
		for (Bill bill : bills) {
			totalPricce += Double.parseDouble(bill.getTotalValue());
		}
		String val = String.valueOf(totalPricce);
		val = val.replaceAll("\\.", "");
		String tmp[] = val.split("E");
		String totalStr = tmp[0];
		if(tmp.length >1){
			for(int i=0; i<Integer.parseInt(tmp[1])-1; i++){
				totalStr += "0";
			}
		}
		return Util.dotPrice(totalStr);
	}
}
